from owslib.wms import WebMapService
from google.appengine.api import memcache
import time
from google.appengine.ext import webapp
import wsgiref.handlers



def regenerate():
  wms = WebMapService("http://reg.bom.gov.au/cgi-bin/reg/ws/gis/users/bomg0022/wxs")

  weather = wms.contents['WEATHER']
  weather_dict = dict([(x.title, x) for x in weather.layers])

  cyclones = weather_dict['Tropical_Cyclone']
  cyclones_dict = dict([(x.title, x) for x in cyclones.layers])

  WA = cyclones_dict['WA']
  WA_dict = dict([(x.title, x) for x in WA.layers])

  cyclones = WA_dict.keys()
  for c in cyclones:
    if c != 'System_2': continue
    cyclone = WA_dict[c]
    cyclone_dict = dict([(x.title, x) for x in cyclone.layers])

    print cyclone.boundingBox
    u_w, u_s, u_e, u_n, proj = cyclone.boundingBox
    u_w, u_e = 180, 0
    u_n, u_s = -90, -0
    layers = []
    for i in cyclone.layers:
      layers.append(i.id)
      if c == "System_2":
        w, s, e, n, proj = cyclone.boundingBox
        print i.title, w, s, e, n
        u_w = min(w, u_w)
        u_e = max(e, u_e)
        u_s = min(s, u_s)
        u_n = max(n, u_n)

    print "BBOX is", (u_w, u_s, u_e, u_n)
    img = wms.getmap(layers=layers,
                     srs=proj,
                     bbox=(u_w, u_s, u_e, u_n),
                     size=(2048, 2048),
                     format='image/png',
                     transparent=True
                     )

    memcache.set('carlos_png', img.content)
    tmp = open('cyclone.tmp').read()
    tmp = tmp.replace('NAME', 'Cyclone Carlos')
    tmp = tmp.replace('WEST', str(u_w))
    tmp = tmp.replace('EAST', str(u_e))
    tmp = tmp.replace('NORTH', str(u_n))
    tmp = tmp.replace('SOUTH', str(u_s))
    tmp = tmp.replace('IMAGE', 'http://mapvisage.appspot.com/cyclone/carlos.png?%s' % time.time())

    memcache.set('carlos_kml', tmp)

class Regenerate(webapp.RequestHandler):
  def get(self):
    regenerate()

class Kml(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
    self.response.out.write(memcache.get('carlos_kml'))

class Image(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'image_png'
    self.response.out.write(memcache.get('carlos_png'))





def main():
  app = webapp.WSGIApplication([
      ('/cyclone/update__', Regenerate),
      ('/cyclone/kml', Kml),
      ('/cyclone/carlos.png', Image),
      ], debug=True)
  wsgiref.handlers.CGIHandler().run(app)

if __name__ == '__main__':
  main()
